<template>
  <div class="finance-report">
    <!-- 页面标题和操作栏 -->
    <div class="report-header">
      <h2>财务报表</h2>
      <div class="header-actions">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          @change="handleDateChange"
        />
        <el-select v-model="reportType" placeholder="报表类型" style="width: 150px; margin-left: 10px;">
          <el-option label="损益表" value="profit" />
          <el-option label="资产负债表" value="balance" />
          <el-option label="现金流量表" value="cashflow" />
          <el-option label="综合报表" value="comprehensive" />
        </el-select>
        <el-button type="primary" @click="refreshData" style="margin-left: 10px;">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
        <el-dropdown style="margin-left: 10px;">
          <el-button type="success">
            导出 <el-icon class="el-icon--right"><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="exportExcel">导出Excel</el-dropdown-item>
              <el-dropdown-item @click="exportPDF">导出PDF</el-dropdown-item>
              <el-dropdown-item @click="exportImage">导出图片</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button @click="printReport" style="margin-left: 10px;">
          <el-icon><Printer /></el-icon>
          打印
        </el-button>
      </div>
    </div>

    <!-- 财务关键指标 -->
    <el-row :gutter="20" class="metrics-cards">
      <el-col :span="6">
        <el-card class="metric-card">
          <div class="metric-content">
            <div class="metric-value">¥{{ formatNumber(totalRevenue) }}</div>
            <div class="metric-label">总收入</div>
            <div class="metric-change positive">+18.5%</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="metric-card">
          <div class="metric-content">
            <div class="metric-value">¥{{ formatNumber(totalExpense) }}</div>
            <div class="metric-label">总支出</div>
            <div class="metric-change negative">+5.2%</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="metric-card">
          <div class="metric-content">
            <div class="metric-value">¥{{ formatNumber(netProfit) }}</div>
            <div class="metric-label">净利润</div>
            <div class="metric-change positive">+25.8%</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="metric-card">
          <div class="metric-content">
            <div class="metric-value">{{ profitMargin }}%</div>
            <div class="metric-label">利润率</div>
            <div class="metric-change positive">+3.2%</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-section">
      <!-- 收支趋势图 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>收支趋势分析</span>
          </template>
          <div ref="revenueExpenseChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
      
      <!-- 利润分析图 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>利润分析</span>
          </template>
          <div ref="profitAnalysisChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="charts-section">
      <!-- 现金流分析 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>现金流分析</span>
          </template>
          <div ref="cashFlowChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
      
      <!-- 费用构成 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>费用构成分析</span>
          </template>
          <div ref="expenseCompositionChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 财务报表详情 -->
    <el-row :gutter="20" class="financial-statements">
      <!-- 损益表 -->
      <el-col :span="8">
        <el-card>
          <template #header>
            <span>损益表摘要</span>
          </template>
          <div class="statement-content">
            <div class="statement-item">
              <span class="item-label">营业收入</span>
              <span class="item-value positive">¥{{ formatNumber(2580000) }}</span>
            </div>
            <div class="statement-item">
              <span class="item-label">营业成本</span>
              <span class="item-value negative">¥{{ formatNumber(1548000) }}</span>
            </div>
            <div class="statement-item">
              <span class="item-label">毛利润</span>
              <span class="item-value positive">¥{{ formatNumber(1032000) }}</span>
            </div>
            <div class="statement-item">
              <span class="item-label">销售费用</span>
              <span class="item-value negative">¥{{ formatNumber(258000) }}</span>
            </div>
            <div class="statement-item">
              <span class="item-label">管理费用</span>
              <span class="item-value negative">¥{{ formatNumber(154800) }}</span>
            </div>
            <div class="statement-item">
              <span class="item-label">财务费用</span>
              <span class="item-value negative">¥{{ formatNumber(25800) }}</span>
            </div>
            <div class="statement-item total">
              <span class="item-label">净利润</span>
              <span class="item-value positive">¥{{ formatNumber(593400) }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 资产负债表 -->
      <el-col :span="8">
        <el-card>
          <template #header>
            <span>资产负债表摘要</span>
          </template>
          <div class="statement-content">
            <div class="statement-section">
              <div class="section-title">资产</div>
              <div class="statement-item">
                <span class="item-label">流动资产</span>
                <span class="item-value">¥{{ formatNumber(3200000) }}</span>
              </div>
              <div class="statement-item">
                <span class="item-label">固定资产</span>
                <span class="item-value">¥{{ formatNumber(1800000) }}</span>
              </div>
              <div class="statement-item total">
                <span class="item-label">总资产</span>
                <span class="item-value">¥{{ formatNumber(5000000) }}</span>
              </div>
            </div>
            <div class="statement-section">
              <div class="section-title">负债及所有者权益</div>
              <div class="statement-item">
                <span class="item-label">流动负债</span>
                <span class="item-value">¥{{ formatNumber(1200000) }}</span>
              </div>
              <div class="statement-item">
                <span class="item-label">长期负债</span>
                <span class="item-value">¥{{ formatNumber(800000) }}</span>
              </div>
              <div class="statement-item">
                <span class="item-label">所有者权益</span>
                <span class="item-value">¥{{ formatNumber(3000000) }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 现金流量表 -->
      <el-col :span="8">
        <el-card>
          <template #header>
            <span>现金流量表摘要</span>
          </template>
          <div class="statement-content">
            <div class="statement-item">
              <span class="item-label">经营活动现金流</span>
              <span class="item-value positive">¥{{ formatNumber(680000) }}</span>
            </div>
            <div class="statement-item">
              <span class="item-label">投资活动现金流</span>
              <span class="item-value negative">¥{{ formatNumber(-120000) }}</span>
            </div>
            <div class="statement-item">
              <span class="item-label">筹资活动现金流</span>
              <span class="item-value negative">¥{{ formatNumber(-80000) }}</span>
            </div>
            <div class="statement-item total">
              <span class="item-label">现金净增加额</span>
              <span class="item-value positive">¥{{ formatNumber(480000) }}</span>
            </div>
            <div class="statement-item">
              <span class="item-label">期初现金余额</span>
              <span class="item-value">¥{{ formatNumber(320000) }}</span>
            </div>
            <div class="statement-item total">
              <span class="item-label">期末现金余额</span>
              <span class="item-value positive">¥{{ formatNumber(800000) }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 财务明细数据表格 -->
    <el-card class="data-table-card">
      <template #header>
        <span>财务明细</span>
      </template>
      <el-table :data="financeDetailData" stripe style="width: 100%">
        <el-table-column prop="date" label="日期" width="120" />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="scope">
            <el-tag :type="getTypeColor(scope.row.type)">{{ scope.row.type }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="科目" width="150" />
        <el-table-column prop="description" label="摘要" width="200" />
        <el-table-column prop="debit" label="借方" width="120">
          <template #default="scope">
            <span v-if="scope.row.debit">¥{{ scope.row.debit }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="credit" label="贷方" width="120">
          <template #default="scope">
            <span v-if="scope.row.credit">¥{{ scope.row.credit }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="balance" label="余额" width="120">
          <template #default="scope">
            ¥{{ scope.row.balance }}
          </template>
        </el-table-column>
        <el-table-column prop="operator" label="操作员" width="100" />
      </el-table>
      
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalRecords"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh, ArrowDown, Printer } from '@element-plus/icons-vue'
import * as echarts from 'echarts'

// 响应式数据
const dateRange = ref<[string, string]>(['2024-01-01', '2024-12-31'])
const reportType = ref('comprehensive')
const currentPage = ref(1)
const pageSize = ref(20)
const totalRecords = ref(150)

// 财务关键指标
const totalRevenue = ref(2580000)
const totalExpense = ref(1986600)
const netProfit = ref(593400)
const profitMargin = ref(23.0)

// 图表引用
const revenueExpenseChart = ref()
const profitAnalysisChart = ref()
const cashFlowChart = ref()
const expenseCompositionChart = ref()

// 财务明细数据
const financeDetailData = ref([
  {
    date: '2024-01-15',
    type: '收入',
    category: '主营业务收入',
    description: '销售商品收入',
    debit: null,
    credit: 55000,
    balance: 2580000,
    operator: '张三'
  },
  {
    date: '2024-01-16',
    type: '支出',
    category: '主营业务成本',
    description: '销售商品成本',
    debit: 33000,
    credit: null,
    balance: 1548000,
    operator: '李四'
  },
  {
    date: '2024-01-17',
    type: '支出',
    category: '销售费用',
    description: '广告宣传费',
    debit: 8000,
    credit: null,
    balance: 258000,
    operator: '王五'
  }
])

// 方法
const formatNumber = (num: number) => {
  return Math.abs(num).toLocaleString()
}

const getTypeColor = (type: string) => {
  const typeMap: Record<string, string> = {
    '收入': 'success',
    '支出': 'danger',
    '转账': 'warning'
  }
  return typeMap[type] || 'info'
}

const handleDateChange = () => {
  refreshData()
}

const refreshData = () => {
  ElMessage.success('数据已刷新')
}

const exportExcel = () => {
  ElMessage.success('Excel导出功能开发中')
}

const exportPDF = () => {
  ElMessage.success('PDF导出功能开发中')
}

const exportImage = () => {
  ElMessage.success('图片导出功能开发中')
}

const printReport = () => {
  window.print()
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
}

// 初始化图表
const initCharts = () => {
  // 收支趋势图
  const revenueExpense = echarts.init(revenueExpenseChart.value)
  revenueExpense.setOption({
    title: {
      text: '月度收支趋势',
      left: 'center',
      textStyle: { fontSize: 14 }
    },
    tooltip: {
      trigger: 'axis',
      formatter: function(params: any) {
        let result = params[0].name + '<br/>'
        params.forEach((item: any) => {
          result += item.seriesName + ': ¥' + item.value + '万<br/>'
        })
        return result
      }
    },
    legend: {
      data: ['收入', '支出'],
      top: 30
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    },
    yAxis: {
      type: 'value',
      name: '金额(万元)'
    },
    series: [
      {
        name: '收入',
        type: 'line',
        data: [215, 230, 224, 218, 135, 147, 260, 182, 191, 234, 290, 330],
        itemStyle: { color: '#67C23A' }
      },
      {
        name: '支出',
        type: 'line',
        data: [165, 180, 174, 168, 105, 117, 200, 142, 151, 184, 220, 250],
        itemStyle: { color: '#F56C6C' }
      }
    ]
  })

  // 利润分析图
  const profitAnalysis = echarts.init(profitAnalysisChart.value)
  profitAnalysis.setOption({
    title: {
      text: '月度利润分析',
      left: 'center',
      textStyle: { fontSize: 14 }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' }
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    },
    yAxis: {
      type: 'value',
      name: '利润(万元)'
    },
    series: [{
      type: 'bar',
      data: [50, 50, 50, 50, 30, 30, 60, 40, 40, 50, 70, 80],
      itemStyle: { color: '#409EFF' }
    }]
  })

  // 现金流分析
  const cashFlow = echarts.init(cashFlowChart.value)
  cashFlow.setOption({
    title: {
      text: '现金流分析',
      left: 'center',
      textStyle: { fontSize: 14 }
    },
    tooltip: {
      trigger: 'axis',
      formatter: function(params: any) {
        let result = params[0].name + '<br/>'
        params.forEach((item: any) => {
          result += item.seriesName + ': ¥' + item.value + '万<br/>'
        })
        return result
      }
    },
    legend: {
      data: ['经营活动', '投资活动', '筹资活动'],
      top: 30
    },
    xAxis: {
      type: 'category',
      data: ['Q1', 'Q2', 'Q3', 'Q4']
    },
    yAxis: {
      type: 'value',
      name: '现金流(万元)'
    },
    series: [
      {
        name: '经营活动',
        type: 'bar',
        data: [170, 180, 165, 165],
        itemStyle: { color: '#67C23A' }
      },
      {
        name: '投资活动',
        type: 'bar',
        data: [-30, -30, -30, -30],
        itemStyle: { color: '#E6A23C' }
      },
      {
        name: '筹资活动',
        type: 'bar',
        data: [-20, -20, -20, -20],
        itemStyle: { color: '#F56C6C' }
      }
    ]
  })

  // 费用构成
  const expenseComposition = echarts.init(expenseCompositionChart.value)
  expenseComposition.setOption({
    title: {
      text: '费用构成分析',
      left: 'center',
      textStyle: { fontSize: 14 }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    series: [{
      name: '费用构成',
      type: 'pie',
      radius: '60%',
      data: [
        { value: 1548, name: '营业成本' },
        { value: 258, name: '销售费用' },
        { value: 155, name: '管理费用' },
        { value: 26, name: '财务费用' }
      ],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  })
}

onMounted(() => {
  nextTick(() => {
    initCharts()
  })
})
</script>

<style scoped>
.finance-report {
  padding: 20px;
}

.report-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.report-header h2 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  align-items: center;
}

.metrics-cards {
  margin-bottom: 20px;
}

.metric-card {
  text-align: center;
}

.metric-content {
  padding: 10px;
}

.metric-value {
  font-size: 28px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 8px;
}

.metric-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 5px;
}

.metric-change {
  font-size: 12px;
  font-weight: bold;
}

.metric-change.positive {
  color: #67C23A;
}

.metric-change.negative {
  color: #F56C6C;
}

.charts-section {
  margin-bottom: 20px;
}

.financial-statements {
  margin-bottom: 20px;
}

.statement-content {
  padding: 10px 0;
}

.statement-section {
  margin-bottom: 20px;
}

.section-title {
  font-weight: bold;
  color: #303133;
  margin-bottom: 10px;
  padding-bottom: 5px;
  border-bottom: 1px solid #ebeef5;
}

.statement-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f5f7fa;
}

.statement-item.total {
  font-weight: bold;
  border-top: 2px solid #409EFF;
  border-bottom: 2px solid #409EFF;
  background-color: #f0f9ff;
}

.item-label {
  color: #606266;
}

.item-value {
  font-weight: bold;
}

.item-value.positive {
  color: #67C23A;
}

.item-value.negative {
  color: #F56C6C;
}

.data-table-card {
  margin-top: 20px;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}

@media (max-width: 768px) {
  .report-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .header-actions {
    margin-top: 10px;
    flex-wrap: wrap;
  }
  
  .metrics-cards .el-col {
    margin-bottom: 10px;
  }
  
  .financial-statements .el-col {
    margin-bottom: 20px;
  }
}
</style>